home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / tos / sed / sed113st.zoo / sed.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-01-01  |  39.4 KB  |  1,829 lines

  1. /*  GNU SED, a batch stream editor.
  2.     Copyright (C) 1989, 1990, 1991 Free Software Foundation, Inc.
  3.  
  4.     This program is free software; you can redistribute it and/or modify
  5.     it under the terms of the GNU General Public License as published by
  6.     the Free Software Foundation; either version 2, or (at your option)
  7.     any later version.
  8.  
  9.     This program is distributed in the hope that it will be useful,
  10.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.     GNU General Public License for more details.
  13.  
  14.     You should have received a copy of the GNU General Public License
  15.     along with this program; if not, write to the Free Software
  16.     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. #ifdef __STDC__
  19. #define VOID void
  20. #else
  21. #define VOID char
  22. #endif
  23.  
  24. #define _GNU_SOURCE
  25. #include <ctype.h>
  26. #ifndef isblank
  27. #define isblank(c) ((c) == ' ' || (c) == '\t')
  28. #endif
  29. #include <stdio.h>
  30. #include <sys/types.h>
  31. #include "regex.h"
  32. #include "getopt.h"
  33. #if defined(STDC_HEADERS)
  34. #include <stdlib.h>
  35. #endif
  36. #if defined(USG) || defined(STDC_HEADERS)
  37. #include <string.h>
  38. #if !defined(STDC_HEADERS)
  39. #include <memory.h>
  40. #endif
  41. #else
  42. #include <strings.h>
  43. #endif
  44.  
  45.  
  46. /*
  47.    GCC 2.3.1 PL1 with MiNTlibs PL25 doesn't seem to like any of the
  48.    following two choices, so when you compile this source on an Atari
  49.    they both are ifdef'ed out. If I interpret the source and include-
  50.    files correctly it doesn't affect the finished executable. However,
  51.    a mistake or two is always easy to make.  :-)
  52.  
  53.    -Daniel Eriksson
  54. */
  55. #ifndef atarist
  56.  
  57.  
  58. #ifndef HAVE_BCOPY
  59. #ifdef HAVE_MEMCPY
  60. #define bcopy(FROM,TO,LEN)  memcpy(TO,FROM,LEN,sizseof(char))
  61. #else
  62. void
  63. bcopy (from, to, len)
  64.      char *from;
  65.      char *to;
  66.      int len;
  67. {
  68.   if (from < to)
  69.     {
  70.       from += len - 1;
  71.       to += len - 1;
  72.       while (len--)
  73.     *to-- = *from--;
  74.     }
  75.   else
  76.     while (len--)
  77.       *to++ = *from++;
  78. }
  79.  
  80. #endif
  81. #endif
  82.  
  83. #endif /* atarist */
  84.  
  85. char *version_string = "GNU sed version 1.13 Atari";
  86.  
  87. /* Struct vector is used to describe a chunk of a sed program.  There is one
  88.    vector for the main program, and one for each { } pair. */
  89. struct vector
  90.   {
  91.     struct sed_cmd *v;
  92.     int v_length;
  93.     int v_allocated;
  94.     struct vector *return_v;
  95.     int return_i;
  96.   };
  97.  
  98.  
  99. /* Goto structure is used to hold both GOTO's and labels.  There are two
  100.    separate lists, one of goto's, called 'jumps', and one of labels, called
  101.    'labels'.
  102.    the V element points to the descriptor for the program-chunk in which the
  103.    goto was encountered.
  104.    the v_index element counts which element of the vector actually IS the
  105.    goto/label.  The first element of the vector is zero.
  106.    the NAME element is the null-terminated name of the label.
  107.    next is the next goto/label in the list. */
  108.  
  109. struct sed_label
  110.   {
  111.     struct vector *v;
  112.     int v_index;
  113.     char *name;
  114.     struct sed_label *next;
  115.   };
  116.  
  117. /* ADDR_TYPE is zero for a null address,
  118.    one if addr_number is valid, or
  119.    two if addr_regex is valid,
  120.    three, if the address is '$'
  121.  
  122.    Other values are undefined.
  123.  */
  124.  
  125. #define ADDR_NULL    0
  126. #define ADDR_NUM    1
  127. #define ADDR_REGEX    2
  128. #define ADDR_LAST    3
  129.  
  130. struct addr
  131.   {
  132.     int addr_type;
  133.     struct re_pattern_buffer *addr_regex;
  134.     int addr_number;
  135.   };
  136.  
  137.  
  138. /* Aflags:  If the low order bit is set, a1 has been
  139.    matched; apply this command until a2 matches.
  140.    If the next bit is set, apply this command to all
  141.    lines that DON'T match the address(es).
  142.  */
  143.  
  144. #define A1_MATCHED_BIT    01
  145. #define ADDR_BANG_BIT    02
  146.  
  147.  
  148. struct sed_cmd
  149.   {
  150.     struct addr a1, a2;
  151.     int aflags;
  152.  
  153.     char cmd;
  154.  
  155.     union
  156.       {
  157.     /* This structure is used for a, i, and c commands */
  158.     struct
  159.       {
  160.         char *text;
  161.         int text_len;
  162.       }
  163.     cmd_txt;
  164.  
  165.     /* This is used for b and t commands */
  166.     struct sed_cmd *label;
  167.  
  168.     /* This for r and w commands */
  169.     FILE *io_file;
  170.  
  171.     /* This for the hairy s command */
  172.     /* For the flags var:
  173.            low order bit means the 'g' option was given,
  174.            next bit means the 'p' option was given,
  175.            and the next bit means a 'w' option was given,
  176.               and wio_file contains the file to write to. */
  177.  
  178. #define S_GLOBAL_BIT    01
  179. #define S_PRINT_BIT    02
  180. #define S_WRITE_BIT    04
  181. #define S_NUM_BIT    010
  182.  
  183.     struct
  184.       {
  185.         struct re_pattern_buffer *regx;
  186.         char *replacement;
  187.         int replace_length;
  188.         int flags;
  189.         int numb;
  190.         FILE *wio_file;
  191.       }
  192.     cmd_regex;
  193.  
  194.     /* This for the y command */
  195.     unsigned char *translate;
  196.  
  197.     /* For { */
  198.     struct vector *sub;
  199.  
  200.     /* for t and b */
  201.     struct sed_label *jump;
  202.       } x;
  203.   };
  204.  
  205. /* Sed operates a line at a time. */
  206. struct line
  207.   {
  208.     char *text;            /* Pointer to line allocated by malloc. */
  209.     int length;            /* Length of text. */
  210.     int alloc;            /* Allocated space for text. */
  211.   };
  212.  
  213. /* This structure holds information about files opend by the 'r', 'w',
  214.    and 's///w' commands.  In paticular, it holds the FILE pointer to
  215.    use, the file's name, a flag that is non-zero if the file is being
  216.    read instead of written. */
  217.  
  218. #define NUM_FPS    32
  219. struct
  220.   {
  221.     FILE *phile;
  222.     char *name;
  223.     int readit;
  224.   }
  225.  
  226. file_ptrs[NUM_FPS];
  227.  
  228.  
  229. #if defined(__STDC__)
  230. # define P_(s) s
  231. #else
  232. # define P_(s) ()
  233. #endif
  234.  
  235. void close_files ();
  236. void panic P_ ((char *str,...));
  237. char *__fp_name P_ ((FILE * fp));
  238. FILE *ck_fopen P_ ((char *name, char *mode));
  239. void ck_fwrite P_ ((char *ptr, int size, int nmemb, FILE * stream));
  240. void ck_fclose P_ ((FILE * stream));
  241. VOID *ck_malloc P_ ((int size));
  242. VOID *ck_realloc P_ ((VOID * ptr, int size));
  243. char *ck_strdup P_ ((char *str));
  244. VOID *init_buffer P_ ((void));
  245. void flush_buffer P_ ((VOID * bb));
  246. int size_buffer P_ ((VOID * b));
  247. void add_buffer P_ ((VOID * bb, char *p, int n));
  248. void add1_buffer P_ ((VOID * bb, int ch));
  249. char *get_buffer P_ ((VOID * bb));
  250.  
  251. void compile_string P_ ((char *str));
  252. void compile_file P_ ((char *str));
  253. struct vector *compile_program P_ ((struct vector * vector));
  254. void bad_prog P_ ((char *why));
  255. int inchar P_ ((void));
  256. void savchar P_ ((int ch));
  257. int compile_address P_ ((struct addr * addr));
  258. void compile_regex P_ ((int slash));
  259. struct sed_label *setup_jump P_ ((struct sed_label * list, struct sed_cmd * cmd, struct vector * vec));
  260. FILE *compile_filename P_ ((int readit));
  261. void read_file P_ ((char *name));
  262. void execute_program P_ ((struct vector * vec));
  263. int match_address P_ ((struct addr * addr));
  264. int read_pattern_space P_ ((void));
  265. void append_pattern_space P_ ((void));
  266. void line_copy P_ ((struct line * from, struct line * to));
  267. void line_append P_ ((struct line * from, struct line * to));
  268. void str_append P_ ((struct line * to, char *string, int length));
  269. void usage P_ ((void));
  270.  
  271. extern char *myname;
  272.  
  273. /* If set, don't write out the line unless explictly told to */
  274. int no_default_output = 0;
  275.  
  276. /* Current input line # */
  277. int input_line_number = 0;
  278.  
  279. /* Are we on the last input file? */
  280. int last_input_file = 0;
  281.  
  282. /* Have we hit EOF on the last input file?  This is used to decide if we
  283.    have hit the '$' address yet. */
  284. int input_EOF = 0;
  285.  
  286. /* non-zero if a quit command has been executed. */
  287. int quit_cmd = 0;
  288.  
  289. /* Have we done any replacements lately?  This is used by the 't' command. */
  290. int replaced = 0;
  291.  
  292. /* How many '{'s are we executing at the moment */
  293. int program_depth = 0;
  294.  
  295. /* The complete compiled SED program that we are going to run */
  296. struct vector *the_program = 0;
  297.  
  298. /* information about labels and jumps-to-labels.  This is used to do
  299.    the required backpatching after we have compiled all the scripts. */
  300. struct sed_label *jumps = 0;
  301. struct sed_label *labels = 0;
  302.  
  303. /* The 'current' input line. */
  304. struct line line;
  305.  
  306. /* An input line that's been stored by later use by the program */
  307. struct line hold;
  308.  
  309. /* A 'line' to append to the current line when it comes time to write it out */
  310. struct line append;
  311.  
  312.  
  313. /* When we're reading a script command from a string, 'prog_start' and
  314.    'prog_end' point to the beginning and end of the string.  This
  315.    would allow us to compile script strings that contain nulls, except
  316.    that script strings are only read from the command line, which is
  317.    null-terminated */
  318. unsigned char *prog_start;
  319. unsigned char *prog_end;
  320.  
  321. /* When we're reading a script command from a string, 'prog_cur' points
  322.    to the current character in the string */
  323. unsigned char *prog_cur;
  324.  
  325. /* This is the name of the current script file.
  326.    It is used for error messages. */
  327. char *prog_name;
  328.  
  329. /* This is the current script file.  If it is zero, we are reading
  330.    from a string stored in 'prog_start' instead.  If both 'prog_file'
  331.    and 'prog_start' are zero, we're in trouble! */
  332. FILE *prog_file;
  333.  
  334. /* this is the number of the current script line that we're compiling.  It is
  335.    used to give out useful and informative error messages. */
  336. int prog_line = 1;
  337.  
  338. /* This is the file pointer that we're currently reading data from.  It may
  339.    be stdin */
  340. FILE *input_file;
  341.  
  342. /* If this variable is non-zero at exit, one or more of the input
  343.    files couldn't be opened. */
  344.  
  345. int bad_input = 0;
  346.  
  347. /* 'an empty regular expression is equivalent to the last regular
  348.    expression read' so we have to keep track of the last regex used.
  349.    Here's where we store a pointer to it (it is only malloc()'d once) */
  350. struct re_pattern_buffer *last_regex;
  351.  
  352. /* Various error messages we may want to print */
  353. static char ONE_ADDR[] = "Command only uses one address";
  354. static char NO_ADDR[] = "Command doesn't take any addresses";
  355. static char LINE_JUNK[] = "Extra characters after command";
  356. static char BAD_EOF[] = "Unexpected End-of-file";
  357. static char NO_REGEX[] = "No previous regular expression";
  358.  
  359. static struct option longopts[] =
  360. {
  361.   {"expression", 1, NULL, 'e'},
  362.   {"file", 1, NULL, 'f'},
  363.   {"quiet", 0, NULL, 'n'},
  364.   {"silent", 0, NULL, 'n'},
  365.   {"version", 0, NULL, 'V'},
  366.   {NULL, 0, NULL, 0}
  367. };
  368.  
  369. /* Yes, the main program, which parses arguments, and does the right
  370.    thing with them; it also inits the temporary storage, etc. */
  371. void
  372. main (argc, argv)
  373.      int argc;
  374.      char **argv;
  375. {
  376.   int opt;
  377.   char *e_strings = NULL;
  378.   int compiled = 0;
  379.   struct sed_label *go, *lbl;
  380.  
  381.   /* see regex.h */
  382.   re_set_syntax (RE_SYNTAX_POSIX_BASIC);
  383.  
  384.  
  385.   myname = argv[0];
  386.   while ((opt = getopt_long (argc, argv, "ne:f:V", longopts, (int *) 0))
  387.      != EOF)
  388.     {
  389.       switch (opt)
  390.     {
  391.     case 'n':
  392.       no_default_output = 1;
  393.       break;
  394.     case 'e':
  395.       if (e_strings == NULL)
  396.         {
  397.           e_strings = ck_malloc (strlen (optarg) + 2);
  398.           strcpy (e_strings, optarg);
  399.         }
  400.       else
  401.         {
  402.           e_strings = ck_realloc (e_strings, strlen (e_strings) + strlen (optarg) + 2);
  403.           strcat (e_strings, optarg);
  404.         }
  405.       strcat (e_strings, "\n");
  406.       compiled = 1;
  407.       break;
  408.     case 'f':
  409.       compile_file (optarg);
  410.       compiled = 1;
  411.       break;
  412.     case 'V':
  413.       fprintf (stderr, "%s\n", version_string);
  414.       break;
  415.     default:
  416.       usage ();
  417.     }
  418.     }
  419.   if (e_strings)
  420.     {
  421.       compile_string (e_strings);
  422.       free (e_strings);
  423.     }
  424.   if (!compiled)
  425.     {
  426.       if (optind == argc)
  427.     usage ();
  428.       compile_string (argv[optind++]);
  429.     }
  430.  
  431.   for (go = jumps; go; go = go->next)
  432.     {
  433.       for (lbl = labels; lbl; lbl = lbl->next)
  434.     if (!strcmp (lbl->name, go->name))
  435.       break;
  436.       if (*go->name && !lbl)
  437.     panic ("Can't find label for jump to '%s'", go->name);
  438.       go->v->v[go->v_index].x.jump = lbl;
  439.     }
  440.  
  441.   line.length = 0;
  442.   line.alloc = 50;
  443.   line.text = ck_malloc (50);
  444.  
  445.   append.length = 0;
  446.   append.alloc = 50;
  447.   append.text = ck_malloc (50);
  448.  
  449.   hold.length = 1;
  450.   hold.alloc = 50;
  451.   hold.text = ck_malloc (50);
  452.   hold.text[0] = '\n';
  453.  
  454.   if (argc <= optind)
  455.     {
  456.       last_input_file++;
  457.       read_file ("-");
  458.     }
  459.   else
  460.     while (optind < argc)
  461.       {
  462.     if (optind == argc - 1)
  463.       last_input_file++;
  464.     read_file (argv[optind]);
  465.     optind++;
  466.     if (quit_cmd)
  467.       break;
  468.       }
  469.   close_files ();
  470.   if (bad_input)
  471.     exit (2);
  472.   exit (0);
  473. }
  474.  
  475. void
  476. close_files ()
  477. {
  478.   int nf;
  479.  
  480.   for (nf = 0; nf < NUM_FPS; nf++)
  481.     {
  482.       if (file_ptrs[nf].phile)
  483.     fclose (file_ptrs[nf].phile);
  484.     }
  485. }
  486.  
  487. /* 'str' is a string (from the command line) that contains a sed command.
  488.    Compile the command, and add it to the end of 'the_program' */
  489. void
  490. compile_string (str)
  491.      char *str;
  492. {
  493.   prog_file = 0;
  494.   prog_line = 0;
  495.   prog_start = prog_cur = (unsigned char *)str;
  496.   prog_end = (unsigned char *)str + strlen (str);
  497.   the_program = compile_program (the_program);
  498. }
  499.  
  500. /* 'str' is the name of a file containing sed commands.  Read them in
  501.    and add them to the end of 'the_program' */
  502. void
  503. compile_file (str)
  504.      char *str;
  505. {
  506.   int ch;
  507.  
  508.   prog_start = prog_cur = prog_end = 0;
  509.   prog_name = str;
  510.   prog_line = 1;
  511.   if (str[0] == '-' && str[1] == '\0')
  512.     prog_file = stdin;
  513.   else
  514.     prog_file = ck_fopen (str, "r");
  515.   ch = getc (prog_file);
  516.   if (ch == '#')
  517.     {
  518.       ch = getc (prog_file);
  519.       if (ch == 'n')
  520.     no_default_output++;
  521.       while (ch != EOF && ch != '\n')
  522.     ch = getc (prog_file);
  523.     }
  524.   else if (ch != EOF)
  525.     ungetc (ch, prog_file);
  526.   the_program = compile_program (the_program);
  527. }
  528.  
  529. #define MORE_CMDS 40
  530.  
  531. /* Read a program (or a subprogram within '{' '}' pairs) in and store
  532.    the compiled form in *'vector'  Return a pointer to the new vector.  */
  533. struct vector *
  534. compile_program (vector)
  535.      struct vector *vector;
  536. {
  537.   struct sed_cmd *cur_cmd;
  538.   int ch;
  539.   int slash;
  540.   VOID *b;
  541.   unsigned char *string;
  542.   int num;
  543.  
  544.   if (!vector)
  545.     {
  546.       vector = (struct vector *) ck_malloc (sizeof (struct vector));
  547.       vector->v = (struct sed_cmd *) ck_malloc (MORE_CMDS * sizeof (struct sed_cmd));
  548.       vector->v_allocated = MORE_CMDS;
  549.       vector->v_length = 0;
  550.       vector->return_v = 0;
  551.       vector->return_i = 0;
  552.     }
  553.   for (;;)
  554.     {
  555.     skip_comment:
  556.       do
  557.     ch = inchar ();
  558.       while (ch != EOF && (isblank (ch) || ch == '\n' || ch == ';'));
  559.       if (ch == EOF)
  560.     break;
  561.       savchar (ch);
  562.  
  563.       if (vector->v_length == vector->v_allocated)
  564.     {
  565.       vector->v = (struct sed_cmd *) ck_realloc ((VOID *) vector->v, (vector->v_length + MORE_CMDS) * sizeof (struct sed_cmd));
  566.       vector->v_allocated += MORE_CMDS;
  567.     }
  568.       cur_cmd = vector->v + vector->v_length;
  569.       vector->v_length++;
  570.  
  571.       cur_cmd->a1.addr_type = 0;
  572.       cur_cmd->a2.addr_type = 0;
  573.       cur_cmd->aflags = 0;
  574.       cur_cmd->cmd = 0;
  575.  
  576.       if (compile_address (&(cur_cmd->a1)))
  577.     {
  578.       ch = inchar ();
  579.       if (ch == ',')
  580.         {
  581.           do
  582.         ch = inchar ();
  583.           while (ch != EOF && isblank (ch));
  584.           savchar (ch);
  585.           if (compile_address (&(cur_cmd->a2)))
  586.         ;
  587.           else
  588.         bad_prog ("Unexpected ','");
  589.         }
  590.       else
  591.         savchar (ch);
  592.     }
  593.       if (cur_cmd->a1.addr_type == ADDR_NUM
  594.       && cur_cmd->a2.addr_type == ADDR_NUM
  595.       && cur_cmd->a2.addr_number < cur_cmd->a1.addr_number)
  596.     cur_cmd->a2.addr_number = cur_cmd->a1.addr_number + 1;
  597.  
  598.       ch = inchar ();
  599.       if (ch == EOF)
  600.     break;
  601.     new_cmd:
  602.       switch (ch)
  603.     {
  604.     case '#':
  605.       if (cur_cmd->a1.addr_type != 0)
  606.         bad_prog (NO_ADDR);
  607.       do
  608.         ch = inchar ();
  609.       while (ch != EOF && ch != '\n');
  610.       vector->v_length--;
  611.       goto skip_comment;
  612.     case '!':
  613.       if (cur_cmd->aflags & ADDR_BANG_BIT)
  614.         bad_prog ("Multiple '!'s");
  615.       cur_cmd->aflags |= ADDR_BANG_BIT;
  616.       do
  617.         ch = inchar ();
  618.       while (ch != EOF && isblank (ch));
  619.       if (ch == EOF)
  620.         bad_prog (BAD_EOF);
  621. #if 0
  622.       savchar (ch);
  623. #endif
  624.       goto new_cmd;
  625.     case 'a':
  626.     case 'i':
  627.       if (cur_cmd->a2.addr_type != 0)
  628.         bad_prog (ONE_ADDR);
  629.       /* Fall Through */
  630.     case 'c':
  631.       cur_cmd->cmd = ch;
  632.       if (inchar () != '\\' || inchar () != '\n')
  633.         bad_prog (LINE_JUNK);
  634.       b = init_buffer ();
  635.       while ((ch = inchar ()) != EOF && ch != '\n')
  636.         {
  637.           if (ch == '\\')
  638.         ch = inchar ();
  639.           add1_buffer (b, ch);
  640.         }
  641.       if (ch != EOF)
  642.         add1_buffer (b, ch);
  643.       num = size_buffer (b);
  644.       string = (unsigned char *) ck_malloc (num);
  645.       bcopy (get_buffer (b), string, num);
  646.       flush_buffer (b);
  647.       cur_cmd->x.cmd_txt.text_len = num;
  648.       cur_cmd->x.cmd_txt.text = (char *) string;
  649.       break;
  650.     case '{':
  651.       cur_cmd->cmd = ch;
  652.       program_depth++;
  653. #if 0
  654.       while ((ch = inchar ()) != EOF && ch != '\n')
  655.         if (!isblank (ch))
  656.           bad_prog (LINE_JUNK);
  657. #endif
  658.       cur_cmd->x.sub = compile_program ((struct vector *) 0);
  659.       /* FOO JF is this the right thing to do?
  660.                almost.  don't forget a return addr.  -t */
  661.       cur_cmd->x.sub->return_v = vector;
  662.       cur_cmd->x.sub->return_i = vector->v_length - 1;
  663.       break;
  664.     case '}':
  665.       if (!program_depth)
  666.         bad_prog ("Unexpected '}'");
  667.       /* a return insn for subprograms -t */
  668.       cur_cmd->cmd = ch;
  669.       if (cur_cmd->a1.addr_type != 0)
  670.         bad_prog ("} doesn't want any addresses");
  671.       while ((ch = inchar ()) != EOF && ch != '\n' && ch != ';')
  672.         if (!isblank (ch))
  673.           bad_prog (LINE_JUNK);
  674.       return vector;
  675.     case ':':
  676.       cur_cmd->cmd = ch;
  677.       if (cur_cmd->a1.addr_type != 0)
  678.         bad_prog (": doesn't want any addresses");
  679.       labels = setup_jump (labels, cur_cmd, vector);
  680.       break;
  681.     case 'b':
  682.     case 't':
  683.       cur_cmd->cmd = ch;
  684.       jumps = setup_jump (jumps, cur_cmd, vector);
  685.       break;
  686.     case 'q':
  687.     case '=':
  688.       if (cur_cmd->a2.addr_type)
  689.         bad_prog (ONE_ADDR);
  690.       /* Fall Through */
  691.     case 'd':
  692.     case 'D':
  693.     case 'g':
  694.     case 'G':
  695.     case 'h':
  696.     case 'H':
  697.     case 'l':
  698.     case 'n':
  699.     case 'N':
  700.     case 'p':
  701.     case 'P':
  702.     case 'x':
  703.       cur_cmd->cmd = ch;
  704.       do
  705.         ch = inchar ();
  706.       while (ch != EOF && isblank (ch) && ch != '\n' && ch != ';');
  707.       if (ch != '\n' && ch != ';' && ch != EOF)
  708.         bad_prog (LINE_JUNK);
  709.       break;
  710.  
  711.     case 'r':
  712.       if (cur_cmd->a2.addr_type != 0)
  713.         bad_prog (ONE_ADDR);
  714.       /* FALL THROUGH */
  715.     case 'w':
  716.       cur_cmd->cmd = ch;
  717.       cur_cmd->x.io_file = compile_filename (ch == 'r');
  718.       break;
  719.  
  720.     case 's':
  721.       cur_cmd->cmd = ch;
  722.       slash = inchar ();
  723.       compile_regex (slash);
  724.  
  725.       cur_cmd->x.cmd_regex.regx = last_regex;
  726.  
  727.       b = init_buffer ();
  728.       while ((ch = inchar ()) != EOF && ch != slash)
  729.         {
  730.           if (ch == '\\')
  731.         {
  732.           int ci;
  733.  
  734.           ci = inchar ();
  735.           if (ci != EOF)
  736.             {
  737.               if (ci != '\n')
  738.             add1_buffer (b, ch);
  739.               add1_buffer (b, ci);
  740.             }
  741.         }
  742.           else
  743.         add1_buffer (b, ch);
  744.         }
  745.       cur_cmd->x.cmd_regex.replace_length = size_buffer (b);
  746.       cur_cmd->x.cmd_regex.replacement = ck_malloc (cur_cmd->x.cmd_regex.replace_length);
  747.       bcopy (get_buffer (b), cur_cmd->x.cmd_regex.replacement, cur_cmd->x.cmd_regex.replace_length);
  748.       flush_buffer (b);
  749.  
  750.       cur_cmd->x.cmd_regex.flags = 0;
  751.       cur_cmd->x.cmd_regex.numb = 0;
  752.  
  753.       if (ch == EOF)
  754.         break;
  755.       do
  756.         {
  757.           ch = inchar ();
  758.           switch (ch)
  759.         {
  760.         case 'p':
  761.           if (cur_cmd->x.cmd_regex.flags & S_PRINT_BIT)
  762.             bad_prog ("multiple 'p' options to 's' command");
  763.           cur_cmd->x.cmd_regex.flags |= S_PRINT_BIT;
  764.           break;
  765.         case 'g':
  766.           if (cur_cmd->x.cmd_regex.flags & S_NUM_BIT)
  767.             cur_cmd->x.cmd_regex.flags &= ~S_NUM_BIT;
  768.           if (cur_cmd->x.cmd_regex.flags & S_GLOBAL_BIT)
  769.             bad_prog ("multiple 'g' options to 's' command");
  770.           cur_cmd->x.cmd_regex.flags |= S_GLOBAL_BIT;
  771.           break;
  772.         case 'w':
  773.           cur_cmd->x.cmd_regex.flags |= S_WRITE_BIT;
  774.           cur_cmd->x.cmd_regex.wio_file = compile_filename (0);
  775.           ch = '\n';
  776.           break;
  777.         case '0':
  778.         case '1':
  779.         case '2':
  780.         case '3':
  781.         case '4':
  782.         case '5':
  783.         case '6':
  784.         case '7':
  785.         case '8':
  786.         case '9':
  787.           if (cur_cmd->x.cmd_regex.flags & S_NUM_BIT)
  788.             bad_prog ("multiple number options to 's' command");
  789.           if ((cur_cmd->x.cmd_regex.flags & S_GLOBAL_BIT) == 0)
  790.             cur_cmd->x.cmd_regex.flags |= S_NUM_BIT;
  791.           num = 0;
  792.           while (isdigit (ch))
  793.             {
  794.               num = num * 10 + ch - '0';
  795.               ch = inchar ();
  796.             }
  797.           savchar (ch);
  798.           cur_cmd->x.cmd_regex.numb = num;
  799.           break;
  800.         case '\n':
  801.         case ';':
  802.         case EOF:
  803.           break;
  804.         default:
  805.           bad_prog ("Unknown option to 's'");
  806.           break;
  807.         }
  808.         }
  809.       while (ch != EOF && ch != '\n' && ch != ';');
  810.       if (ch == EOF)
  811.         break;
  812.       break;
  813.  
  814.     case 'y':
  815.       cur_cmd->cmd = ch;
  816.       string = (unsigned char *) ck_malloc (256);
  817.       for (num = 0; num < 256; num++)
  818.         string[num] = num;
  819.       b = init_buffer ();
  820.       slash = inchar ();
  821.       while ((ch = inchar ()) != EOF && ch != slash)
  822.         add1_buffer (b, ch);
  823.       cur_cmd->x.translate = string;
  824.       string = (unsigned char *) get_buffer (b);
  825.       for (num = size_buffer (b); num; --num)
  826.         {
  827.           ch = inchar ();
  828.           if (ch == EOF)
  829.         bad_prog (BAD_EOF);
  830.           if (ch == slash)
  831.         bad_prog ("strings for y command are different lengths");
  832.           cur_cmd->x.translate[*string++] = ch;
  833.         }
  834.       flush_buffer (b);
  835.       if (inchar () != slash || ((ch = inchar ()) != EOF && ch != '\n' && ch != ';'))
  836.         bad_prog (LINE_JUNK);
  837.       break;
  838.  
  839.     default:
  840.       bad_prog ("Unknown command");
  841.     }
  842.     }
  843.   return vector;
  844. }
  845.  
  846. /* Complain about a programming error and exit. */
  847. void
  848. bad_prog (why)
  849.      char *why;
  850. {
  851.   if (prog_line)
  852.     fprintf (stderr, "%s: file %s line %d: %s\n", myname, prog_name, prog_line, why);
  853.   else
  854.     fprintf (stderr, "%s: %s\n", myname, why);
  855.   exit (1);
  856. }
  857.  
  858. /* Read the next character from the program.  Return EOF if there isn't
  859.    anything to read.  Keep prog_line up to date, so error messages can
  860.    be meaningful. */
  861. int
  862. inchar ()
  863. {
  864.   int ch;
  865.   if (prog_file)
  866.     {
  867.       if (feof (prog_file))
  868.     return EOF;
  869.       else
  870.     ch = getc (prog_file);
  871.     }
  872.   else
  873.     {
  874.       if (!prog_cur)
  875.     return EOF;
  876.       else if (prog_cur == prog_end)
  877.     {
  878.       ch = EOF;
  879.       prog_cur = 0;
  880.     }
  881.       else
  882.     ch = *prog_cur++;
  883.     }
  884.   if (ch == '\n' && prog_line)
  885.     prog_line++;
  886.   return ch;
  887. }
  888.  
  889. /* unget 'ch' so the next call to inchar will return it.  'ch' must not be
  890.    EOF or anything nasty like that. */
  891. void
  892. savchar (ch)
  893.      int ch;
  894. {
  895.   if (ch == EOF)
  896.     return;
  897.   if (ch == '\n' && prog_line > 1)
  898.     --prog_line;
  899.   if (prog_file)
  900.     ungetc (ch, prog_file);
  901.   else
  902.     *--prog_cur = ch;
  903. }
  904.  
  905.  
  906. /* Try to read an address for a sed command.  If it succeeeds,
  907.    return non-zero and store the resulting address in *'addr'.
  908.    If the input doesn't look like an address read nothing
  909.    and return zero. */
  910. int
  911. compile_address (addr)
  912.      struct addr *addr;
  913. {
  914.   int ch;
  915.   int num;
  916.  
  917.   ch = inchar ();
  918.  
  919.   if (isdigit (ch))
  920.     {
  921.       num = ch - '0';
  922.       while ((ch = inchar ()) != EOF && isdigit (ch))
  923.     num = num * 10 + ch - '0';
  924.       while (ch != EOF && isblank (ch))
  925.     ch = inchar ();
  926.       savchar (ch);
  927.       addr->addr_type = ADDR_NUM;
  928.       addr->addr_number = num;
  929.       return 1;
  930.     }
  931.   else if (ch == '/' || ch == '\\')
  932.     {
  933.       addr->addr_type = ADDR_REGEX;
  934.       if (ch == '\\')
  935.     ch = inchar ();
  936.       compile_regex (ch);
  937.       addr->addr_regex = last_regex;
  938.       do
  939.     ch = inchar ();
  940.       while (ch != EOF && isblank (ch));
  941.       savchar (ch);
  942.       return 1;
  943.     }
  944.   else if (ch == '$')
  945.     {
  946.       addr->addr_type = ADDR_LAST;
  947.       do
  948.     ch = inchar ();
  949.       while (ch != EOF && isblank (ch));
  950.       savchar (ch);
  951.       return 1;
  952.     }
  953.   else
  954.     savchar (ch);
  955.   return 0;
  956. }
  957.  
  958. void
  959. compile_regex (slash)
  960.      int slash;
  961. {
  962.   VOID *b;
  963.   int ch;
  964.   int in_char_class = 0;
  965.  
  966.   b = init_buffer ();
  967.   while ((ch = inchar ()) != EOF && (ch != slash || in_char_class))
  968.     {
  969.       if (ch == '^')
  970.     {
  971.       if (size_buffer (b) == 0)
  972.         {
  973.           add1_buffer (b, '\\');
  974.           add1_buffer (b, '`');
  975.         }
  976.       else
  977.         add1_buffer (b, ch);
  978.       continue;
  979.     }
  980.       else if (ch == '$')
  981.     {
  982.       ch = inchar ();
  983.       savchar (ch);
  984.       if (ch == slash)
  985.         {
  986.           add1_buffer (b, '\\');
  987.           add1_buffer (b, '\'');
  988.         }
  989.       else
  990.         add1_buffer (b, '$');
  991.       continue;
  992.     }
  993.       else if (ch == '[')
  994.     {
  995.       add1_buffer (b, ch);
  996.       in_char_class = 1;
  997.       continue;
  998.     }
  999.       else if (ch == ']')
  1000.     {
  1001.       add1_buffer (b, ch);
  1002.       in_char_class = 0;
  1003.       continue;
  1004.     }
  1005.       else if (ch != '\\' || in_char_class)
  1006.     {
  1007.       add1_buffer (b, ch);
  1008.       continue;
  1009.     }
  1010.       ch = inchar ();
  1011.       switch (ch)
  1012.     {
  1013.     case 'n':
  1014.       add1_buffer (b, '\n');
  1015.       break;
  1016. #if 0
  1017.     case 'b':
  1018.       add1_buffer (b, '\b');
  1019.       break;
  1020.     case 'f':
  1021.       add1_buffer (b, '\f');
  1022.       break;
  1023.     case 'r':
  1024.       add1_buffer (b, '\r');
  1025.       break;
  1026.     case 't':
  1027.       add1_buffer (b, '\t');
  1028.       break;
  1029. #endif /* 0 */
  1030.     case EOF:
  1031.       break;
  1032.     default:
  1033.       add1_buffer (b, '\\');
  1034.       add1_buffer (b, ch);
  1035.       break;
  1036.     }
  1037.     }
  1038.   if (ch == EOF)
  1039.     bad_prog (BAD_EOF);
  1040.   if (size_buffer (b))
  1041.     {
  1042.       last_regex = (struct re_pattern_buffer *) ck_malloc (sizeof (struct re_pattern_buffer));
  1043.       last_regex->allocated = size_buffer (b) + 10;
  1044.       last_regex->buffer =
  1045.     (unsigned char *) ck_malloc (last_regex->allocated);
  1046.       last_regex->fastmap = ck_malloc (256);
  1047.       last_regex->translate = 0;
  1048.       re_compile_pattern (get_buffer (b), size_buffer (b), last_regex);
  1049.     }
  1050.   else if (!last_regex)
  1051.     bad_prog (NO_REGEX);
  1052.   flush_buffer (b);
  1053. }
  1054.  
  1055. /* Store a label (or label reference) created by a ':', 'b', or 't'
  1056.    comand so that the jump to/from the lable can be backpatched after
  1057.    compilation is complete */
  1058. struct sed_label *
  1059. setup_jump (list, cmd, vec)
  1060.      struct sed_label *list;
  1061.      struct sed_cmd *cmd;
  1062.      struct vector *vec;
  1063. {
  1064.   struct sed_label *tmp;
  1065.   VOID *b;
  1066.   int ch;
  1067.  
  1068.   b = init_buffer ();
  1069.   while ((ch = inchar ()) != EOF && isblank (ch))
  1070.     ;
  1071.   while (ch != EOF && ch != '\n')
  1072.     {
  1073.       add1_buffer (b, ch);
  1074.       ch = inchar ();
  1075.     }
  1076.   savchar (ch);
  1077.   add1_buffer (b, '\0');
  1078.   tmp = (struct sed_label *) ck_malloc (sizeof (struct sed_label));
  1079.   tmp->v = vec;
  1080.   tmp->v_index = cmd - vec->v;
  1081.   tmp->name = ck_strdup (get_buffer (b));
  1082.   tmp->next = list;
  1083.   flush_buffer (b);
  1084.   return tmp;
  1085. }
  1086.  
  1087. /* read in a filename for a 'r', 'w', or 's///w' command, and
  1088.    update the internal structure about files.  The file is
  1089.    opened if it isn't already open. */
  1090. FILE *
  1091. compile_filename (readit)
  1092.      int readit;
  1093. {
  1094.   char *file_name;
  1095.   int n;
  1096.   VOID *b;
  1097.   int ch;
  1098.  
  1099.   if (inchar () != ' ')
  1100.     bad_prog ("missing ' ' before filename");
  1101.   b = init_buffer ();
  1102.   while ((ch = inchar ()) != EOF && ch != '\n')
  1103.     add1_buffer (b, ch);
  1104.   add1_buffer (b, '\0');
  1105.   file_name = get_buffer (b);
  1106.   for (n = 0; n < NUM_FPS; n++)
  1107.     {
  1108.       if (!file_ptrs[n].name)
  1109.     break;
  1110.       if (!strcmp (file_ptrs[n].name, file_name))
  1111.     {
  1112.       if (file_ptrs[n].readit != readit)
  1113.         bad_prog ("Can't open file for both reading and writing");
  1114.       flush_buffer (b);
  1115.       return file_ptrs[n].phile;
  1116.     }
  1117.     }
  1118.   if (n < NUM_FPS)
  1119.     {
  1120.       file_ptrs[n].name = ck_strdup (file_name);
  1121.       file_ptrs[n].readit = readit;
  1122.       if (!readit)
  1123.     file_ptrs[n].phile = ck_fopen (file_name, "a");
  1124.       else if (access (file_name, 4) == 0)
  1125.     file_ptrs[n].phile = ck_fopen (file_name, "r");
  1126.       else
  1127.     file_ptrs[n].phile = ck_fopen ("/dev/null", "r");
  1128.       flush_buffer (b);
  1129.       return file_ptrs[n].phile;
  1130.     }
  1131.   else
  1132.     {
  1133.       bad_prog ("Hopelessely evil compiled in limit on number of open files.  re-compile sed");
  1134.       return 0;
  1135.     }
  1136. }
  1137.  
  1138. /* Parse a filename given by a 'r' 'w' or 's///w' command. */
  1139. void
  1140. read_file (name)
  1141.      char *name;
  1142. {
  1143.   if (*name == '-' && name[1] == '\0')
  1144.     input_file = stdin;
  1145.   else
  1146.     {
  1147.       input_file = fopen (name, "r");
  1148.       if (input_file == 0)
  1149.     {
  1150.       extern int errno;
  1151.       extern char *sys_errlist[];
  1152.       extern int sys_nerr;
  1153.  
  1154.       char *ptr;
  1155.  
  1156.       ptr = (errno >= 0 && errno < sys_nerr) ? sys_errlist[errno] : "Unknown error code";
  1157.       bad_input++;
  1158.       fprintf (stderr, "%s: can't read %s: %s\n", myname, name, ptr);
  1159.  
  1160.       return;
  1161.     }
  1162.     }
  1163.   while (read_pattern_space ())
  1164.     {
  1165.       execute_program (the_program);
  1166.       if (!no_default_output)
  1167.     ck_fwrite (line.text, 1, line.length, stdout);
  1168.       if (append.length)
  1169.     {
  1170.       ck_fwrite (append.text, 1, append.length, stdout);
  1171.       append.length = 0;
  1172.     }
  1173.       if (quit_cmd)
  1174.     break;
  1175.     }
  1176.   ck_fclose (input_file);
  1177. }
  1178.  
  1179. static char *
  1180. chr_pos (str, chr, len)
  1181.      char *str;
  1182.      char chr;
  1183.      int len;
  1184. {
  1185.   while (len--)
  1186.     if (*str++ == chr)
  1187.       return --str;
  1188. }
  1189.  
  1190. static void
  1191. chr_copy (dest, src, len)
  1192.      char *dest;
  1193.      char *src;
  1194.      int len;
  1195. {
  1196.   while (len--)
  1197.     *dest++ = *src++;
  1198. }
  1199.  
  1200. /* Execute the program 'vec' on the current input line. */
  1201. static struct re_registers regs =
  1202. {0, 0, 0};
  1203.  
  1204. void
  1205. execute_program (vec)
  1206.      struct vector *vec;
  1207. {
  1208.   struct sed_cmd *cur_cmd;
  1209.   int n;
  1210.   int addr_matched;
  1211.   static int end_cycle;
  1212.  
  1213.   int start;
  1214.   int remain;
  1215.   int offset;
  1216.  
  1217.   static struct line tmp;
  1218.   struct line t;
  1219.   char *rep, *rep_end, *rep_next, *rep_cur;
  1220.  
  1221.   int count;
  1222.   struct vector *restart_vec = vec;
  1223.  
  1224. restart:
  1225.   vec = restart_vec;
  1226.   count = 0;
  1227.  
  1228.   end_cycle = 0;
  1229.  
  1230.   for (cur_cmd = vec->v, n = vec->v_length; n; cur_cmd++, n--)
  1231.     {
  1232.  
  1233.     exe_loop:
  1234.       addr_matched = 0;
  1235.       if (cur_cmd->aflags & A1_MATCHED_BIT)
  1236.     {
  1237.       addr_matched = 1;
  1238.       if (match_address (&(cur_cmd->a2)))
  1239.         cur_cmd->aflags &= ~A1_MATCHED_BIT;
  1240.     }
  1241.       else if (match_address (&(cur_cmd->a1)))
  1242.     {
  1243.       addr_matched = 1;
  1244.       if (cur_cmd->a2.addr_type != ADDR_NULL)
  1245.         if (!match_address (&(cur_cmd->a2)))
  1246.           cur_cmd->aflags |= A1_MATCHED_BIT;
  1247.  
  1248.     }
  1249.       if (cur_cmd->aflags & ADDR_BANG_BIT)
  1250.     addr_matched = !addr_matched;
  1251.       if (!addr_matched)
  1252.     continue;
  1253.       switch (cur_cmd->cmd)
  1254.     {
  1255.     case '{':        /* Execute sub-program */
  1256.       if (cur_cmd->x.sub->v_length)
  1257.         {
  1258.           vec = cur_cmd->x.sub;
  1259.           cur_cmd = vec->v;
  1260.           n = vec->v_length;
  1261.           goto exe_loop;
  1262.         }
  1263.       break;
  1264.  
  1265.     case '}':
  1266.       cur_cmd = vec->return_v->v + vec->return_i;
  1267.       n = vec->return_v->v_length - vec->return_i;
  1268.       vec = vec->return_v;
  1269.       break;
  1270.  
  1271.     case ':':        /* Executing labels is easy. */
  1272.       break;
  1273.  
  1274.     case '=':
  1275.       printf ("%d\n", input_line_number);
  1276.       break;
  1277.  
  1278.     case 'a':
  1279.       while (append.alloc - append.length < cur_cmd->x.cmd_txt.text_len)
  1280.         {
  1281.           append.alloc *= 2;
  1282.           append.text = ck_realloc (append.text, append.alloc);
  1283.         }
  1284.       bcopy (cur_cmd->x.cmd_txt.text, append.text + append.length, cur_cmd->x.cmd_txt.text_len);
  1285.       append.length += cur_cmd->x.cmd_txt.text_len;
  1286.       break;
  1287.  
  1288.     case 'b':
  1289.       if (!cur_cmd->x.jump)
  1290.         end_cycle++;
  1291.       else
  1292.         {
  1293.           struct sed_label *j = cur_cmd->x.jump;
  1294.  
  1295.           n = j->v->v_length - j->v_index;
  1296.           cur_cmd = j->v->v + j->v_index;
  1297.           goto exe_loop;
  1298.         }
  1299.       break;
  1300.  
  1301.     case 'c':
  1302.       line.length = 0;
  1303.       if (!((cur_cmd->aflags & A1_MATCHED_BIT)
  1304.         || no_default_output))
  1305.         ck_fwrite (cur_cmd->x.cmd_txt.text, 1, cur_cmd->x.cmd_txt.text_len, stdout);
  1306.       end_cycle++;
  1307.       break;
  1308.  
  1309.     case 'd':
  1310.       line.length = 0;
  1311.       end_cycle++;
  1312.       break;
  1313.  
  1314.     case 'D':
  1315.       {
  1316.         char *tmp;
  1317.         int newlength;
  1318.  
  1319.         tmp = chr_pos (line.text, '\n', line.length);
  1320.         newlength = line.length - (tmp - line.text) - 1;
  1321.         if (newlength)
  1322.           {
  1323.         chr_copy (line.text, tmp + 1, newlength);
  1324.         line.length = newlength;
  1325.         goto restart;
  1326.           }
  1327.         line.length = 0;
  1328.         end_cycle++;
  1329.       }
  1330.       break;
  1331.  
  1332.     case 'g':
  1333.       line_copy (&hold, &line);
  1334.       break;
  1335.  
  1336.     case 'G':
  1337.       line_append (&hold, &line);
  1338.       break;
  1339.  
  1340.     case 'h':
  1341.       line_copy (&line, &hold);
  1342.       break;
  1343.  
  1344.     case 'H':
  1345.       line_append (&line, &hold);
  1346.       break;
  1347.  
  1348.     case 'i':
  1349.       if (!no_default_output)
  1350.         ck_fwrite (cur_cmd->x.cmd_txt.text, 1,
  1351.                cur_cmd->x.cmd_txt.text_len, stdout);
  1352.       break;
  1353.  
  1354.     case 'l':
  1355.       {
  1356.         char *tmp;
  1357.         int n;
  1358.         int width = 0;
  1359.  
  1360.         n = line.length;
  1361.         tmp = line.text;
  1362.         /* Use --n so this'll skip the trailing newline */
  1363.         while (--n)
  1364.           {
  1365.         if (width > 77)
  1366.           {
  1367.             width = 0;
  1368.             putchar ('\n');
  1369.           }
  1370.         if (*tmp == '\\')
  1371.           {
  1372.             printf ("\\\\");
  1373.             width += 2;
  1374.           }
  1375.         else if (isprint (*tmp))
  1376.           {
  1377.             putchar (*tmp);
  1378.             width++;
  1379.           }
  1380.         else
  1381.           switch (*tmp)
  1382.             {
  1383. #if 0
  1384.               /* Should print \00 instead of \0 because (a) POSIX */
  1385.               /* requires it, and (b) this way \01 is unambiguous.  */
  1386.             case '\0':
  1387.               printf ("\\0");
  1388.               width += 2;
  1389.               break;
  1390. #endif
  1391.             case 007:
  1392.               printf ("\\a");
  1393.               width += 2;
  1394.               break;
  1395.             case '\b':
  1396.               printf ("\\b");
  1397.               width += 2;
  1398.               break;
  1399.             case '\f':
  1400.               printf ("\\f");
  1401.               width += 2;
  1402.               break;
  1403.             case '\n':
  1404.               printf ("\\n");
  1405.               width += 2;
  1406.               break;
  1407.             case '\r':
  1408.               printf ("\\r");
  1409.               width += 2;
  1410.               break;
  1411.             case '\t':
  1412.               printf ("\\t");
  1413.               width += 2;
  1414.               break;
  1415.             case '\v':
  1416.               printf ("\\v");
  1417.               width += 2;
  1418.               break;
  1419.             default:
  1420.               printf ("\\%02x", (*tmp) & 0xFF);
  1421.               width += 2;
  1422.               break;
  1423.             }
  1424.         tmp++;
  1425.           }
  1426.         putchar ('\n');
  1427.       }
  1428.       break;
  1429.  
  1430.     case 'n':
  1431.       if (feof (input_file))
  1432.         goto quit;
  1433.       if (!no_default_output)
  1434.         ck_fwrite (line.text, 1, line.length, stdout);
  1435.       read_pattern_space ();
  1436.       break;
  1437.  
  1438.     case 'N':
  1439.       if (feof (input_file))
  1440.         goto quit;
  1441.       append_pattern_space ();
  1442.       break;
  1443.  
  1444.     case 'p':
  1445.       ck_fwrite (line.text, 1, line.length, stdout);
  1446.       break;
  1447.  
  1448.     case 'P':
  1449.       {
  1450.         char *tmp;
  1451.  
  1452.         tmp = chr_pos (line.text, '\n', line.length);
  1453.         ck_fwrite (line.text, 1,
  1454.                tmp ? tmp - line.text + 1
  1455.                : line.length, stdout);
  1456.       }
  1457.       break;
  1458.  
  1459.     case 'q':
  1460.     quit:
  1461.       quit_cmd++;
  1462.       end_cycle++;
  1463.       break;
  1464.  
  1465.     case 'r':
  1466.       {
  1467.         int n = 0;
  1468.  
  1469.         rewind (cur_cmd->x.io_file);
  1470.         do
  1471.           {
  1472.         append.length += n;
  1473.         if (append.length == append.alloc)
  1474.           {
  1475.             append.alloc *= 2;
  1476.             append.text = ck_realloc (append.text, append.alloc);
  1477.           }
  1478.         n = fread (append.text + append.length, sizeof (char),
  1479.                append.alloc - append.length,
  1480.                cur_cmd->x.io_file);
  1481.           }
  1482.         while (n > 0);
  1483.         if (ferror (cur_cmd->x.io_file))
  1484.           panic ("Read error on input file to 'r' command");
  1485.       }
  1486.       break;
  1487.  
  1488.     case 's':
  1489.       if (!tmp.alloc)
  1490.         {
  1491.           tmp.alloc = 50;
  1492.           tmp.text = ck_malloc (50);
  1493.         }
  1494.       count = 0;
  1495.       start = 0;
  1496.       remain = line.length - 1;
  1497.       tmp.length = 0;
  1498.       rep = cur_cmd->x.cmd_regex.replacement;
  1499.       rep_end = rep + cur_cmd->x.cmd_regex.replace_length;
  1500.  
  1501.       while ((offset = re_search (cur_cmd->x.cmd_regex.regx,
  1502.                       line.text,
  1503.                       line.length - 1,
  1504.                       start,
  1505.                       remain,
  1506.                       ®s)) >= 0)
  1507.         {
  1508.           count++;
  1509.           if (offset - start)
  1510.         str_append (&tmp, line.text + start, offset - start);
  1511.  
  1512.           if (cur_cmd->x.cmd_regex.flags & S_NUM_BIT)
  1513.         {
  1514.           if (count != cur_cmd->x.cmd_regex.numb)
  1515.             {
  1516.               str_append (&tmp, line.text + regs.start[0], regs.end[0] - regs.start[0]);
  1517.               start = (offset == regs.end[0] ? offset + 1 : regs.end[0]);
  1518.               remain = (line.length - 1) - start;
  1519.               continue;
  1520.             }
  1521.         }
  1522.  
  1523.           for (rep_next = rep_cur = rep; rep_next < rep_end; rep_next++)
  1524.         {
  1525.           if (*rep_next == '&')
  1526.             {
  1527.               if (rep_next - rep_cur)
  1528.             str_append (&tmp, rep_cur, rep_next - rep_cur);
  1529.               str_append (&tmp, line.text + regs.start[0], regs.end[0] - regs.start[0]);
  1530.               rep_cur = rep_next + 1;
  1531.             }
  1532.           else if (*rep_next == '\\')
  1533.             {
  1534.               if (rep_next - rep_cur)
  1535.             str_append (&tmp, rep_cur, rep_next - rep_cur);
  1536.               rep_next++;
  1537.               if (rep_next != rep_end)
  1538.             {
  1539.               int n;
  1540.  
  1541.               if (*rep_next >= '0' && *rep_next <= '9')
  1542.                 {
  1543.                   n = *rep_next - '0';
  1544.                   str_append (&tmp, line.text + regs.start[n], regs.end[n] - regs.start[n]);
  1545.                 }
  1546.               else
  1547.                 str_append (&tmp, rep_next, 1);
  1548.             }
  1549.               rep_cur = rep_next + 1;
  1550.             }
  1551.         }
  1552.           if (rep_next - rep_cur)
  1553.         str_append (&tmp, rep_cur, rep_next - rep_cur);
  1554.           if (offset == regs.end[0])
  1555.         {
  1556.           str_append (&tmp, line.text + offset, 1);
  1557.           ++regs.end[0];
  1558.         }
  1559.           start = regs.end[0];
  1560.  
  1561.           remain = (line.length - 1) - start;
  1562.           if (remain < 0)
  1563.         break;
  1564.           if (!(cur_cmd->x.cmd_regex.flags & S_GLOBAL_BIT))
  1565.         break;
  1566.         }
  1567.       if (!count)
  1568.         break;
  1569.       replaced = 1;
  1570.       str_append (&tmp, line.text + start, remain + 1);
  1571.       t.text = line.text;
  1572.       t.length = line.length;
  1573.       t.alloc = line.alloc;
  1574.       line.text = tmp.text;
  1575.       line.length = tmp.length;
  1576.       line.alloc = tmp.alloc;
  1577.       tmp.text = t.text;
  1578.       tmp.length = t.length;
  1579.       tmp.alloc = t.alloc;
  1580.       if (cur_cmd->x.cmd_regex.flags & S_WRITE_BIT)
  1581.         ck_fwrite (line.text, 1, line.length,
  1582.                cur_cmd->x.cmd_regex.wio_file);
  1583.       if (cur_cmd->x.cmd_regex.flags & S_PRINT_BIT)
  1584.         ck_fwrite (line.text, 1, line.length, stdout);
  1585.       break;
  1586.  
  1587.     case 't':
  1588.       if (replaced)
  1589.         {
  1590.           replaced = 0;
  1591.           if (!cur_cmd->x.jump)
  1592.         end_cycle++;
  1593.           else
  1594.         {
  1595.           struct sed_label *j = cur_cmd->x.jump;
  1596.  
  1597.           n = j->v->v_length - j->v_index;
  1598.           cur_cmd = j->v->v + j->v_index;
  1599.           goto exe_loop;
  1600.         }
  1601.         }
  1602.       break;
  1603.  
  1604.     case 'w':
  1605.       ck_fwrite (line.text, 1, line.length, cur_cmd->x.io_file);
  1606.       break;
  1607.  
  1608.     case 'x':
  1609.       {
  1610.         struct line tmp;
  1611.  
  1612.         tmp = line;
  1613.         line = hold;
  1614.         hold = tmp;
  1615.       }
  1616.       break;
  1617.  
  1618.     case 'y':
  1619.       {
  1620.         unsigned char *p, *e;
  1621.  
  1622.         for (p = (unsigned char *) (line.text), e = p + line.length; p < e; p++)
  1623.           *p = cur_cmd->x.translate[*p];
  1624.       }
  1625.       break;
  1626.  
  1627.     default:
  1628.       panic ("INTERNAL ERROR: Bad cmd %c", cur_cmd->cmd);
  1629.     }
  1630.       if (end_cycle)
  1631.     break;
  1632.     }
  1633. }
  1634.  
  1635.  
  1636. /* Return non-zero if the current line matches the address
  1637.    pointed to by 'addr'. */
  1638. int
  1639. match_address (addr)
  1640.      struct addr *addr;
  1641. {
  1642.   switch (addr->addr_type)
  1643.     {
  1644.     case ADDR_NULL:
  1645.       return 1;
  1646.     case ADDR_NUM:
  1647.       return (input_line_number == addr->addr_number);
  1648.  
  1649.     case ADDR_REGEX:
  1650.       return (re_search (addr->addr_regex,
  1651.              line.text,
  1652.              line.length - 1,
  1653.              0,
  1654.              line.length - 1,
  1655.              (struct re_registers *) 0) >= 0) ? 1 : 0;
  1656.  
  1657.     case ADDR_LAST:
  1658.       return (input_EOF) ? 1 : 0;
  1659.  
  1660.     default:
  1661.       panic ("INTERNAL ERROR: bad address type");
  1662.       break;
  1663.     }
  1664.   return -1;
  1665. }
  1666.  
  1667. /* Read in the next line of input, and store it in the
  1668.    pattern space.  Return non-zero if this is the last line of input */
  1669.  
  1670. int
  1671. read_pattern_space ()
  1672. {
  1673.   int n;
  1674.   char *p;
  1675.   int ch;
  1676.  
  1677.   p = line.text;
  1678.   n = line.alloc;
  1679.  
  1680.   if (feof (input_file))
  1681.     return 0;
  1682.   input_line_number++;
  1683.   replaced = 0;
  1684.   for (;;)
  1685.     {
  1686.       if (n == 0)
  1687.     {
  1688.       line.text = ck_realloc (line.text, line.alloc * 2);
  1689.       p = line.text + line.alloc;
  1690.       n = line.alloc;
  1691.       line.alloc *= 2;
  1692.     }
  1693.       ch = getc (input_file);
  1694.       if (ch == EOF)
  1695.     {
  1696.       if (n == line.alloc)
  1697.         return 0;
  1698.       *p++ = '\n';
  1699.       --n;
  1700.       line.length = line.alloc - n;
  1701.       if (last_input_file)
  1702.         input_EOF++;
  1703.       return 1;
  1704.     }
  1705.       *p++ = ch;
  1706.       --n;
  1707.       if (ch == '\n')
  1708.     {
  1709.       line.length = line.alloc - n;
  1710.       break;
  1711.     }
  1712.     }
  1713.   ch = getc (input_file);
  1714.   if (ch != EOF)
  1715.     ungetc (ch, input_file);
  1716.   else if (last_input_file)
  1717.     input_EOF++;
  1718.   return 1;
  1719. }
  1720.  
  1721. /* Inplement the 'N' command, which appends the next line of input to
  1722.    the pattern space. */
  1723. void
  1724. append_pattern_space ()
  1725. {
  1726.   char *p;
  1727.   int n;
  1728.   int ch;
  1729.  
  1730.   p = line.text + line.length;
  1731.   n = line.alloc - line.length;
  1732.  
  1733.   input_line_number++;
  1734.   replaced = 0;
  1735.   for (;;)
  1736.     {
  1737.       ch = getc (input_file);
  1738.       if (ch == EOF)
  1739.     {
  1740.       if (n == line.alloc)
  1741.         return;
  1742.       *p++ = '\n';
  1743.       --n;
  1744.       line.length = line.alloc - n;
  1745.       if (last_input_file)
  1746.         input_EOF++;
  1747.       return;
  1748.     }
  1749.       *p++ = ch;
  1750.       --n;
  1751.       if (ch == '\n')
  1752.     {
  1753.       line.length = line.alloc - n;
  1754.       break;
  1755.     }
  1756.       if (n == 0)
  1757.     {
  1758.       line.text = ck_realloc (line.text, line.alloc * 2);
  1759.       p = line.text + line.alloc;
  1760.       n = line.alloc;
  1761.       line.alloc *= 2;
  1762.     }
  1763.     }
  1764.   ch = getc (input_file);
  1765.   if (ch != EOF)
  1766.     ungetc (ch, input_file);
  1767.   else if (last_input_file)
  1768.     input_EOF++;
  1769. }
  1770.  
  1771. /* Copy the contents of the line 'from' into the line 'to'.
  1772.    This destroys the old contents of 'to'.  It will still work
  1773.    if the line 'from' contains nulls. */
  1774. void
  1775. line_copy (from, to)
  1776.      struct line *from, *to;
  1777. {
  1778.   if (from->length > to->alloc)
  1779.     {
  1780.       to->alloc = from->length;
  1781.       to->text = ck_realloc (to->text, to->alloc);
  1782.     }
  1783.   bcopy (from->text, to->text, from->length);
  1784.   to->length = from->length;
  1785. }
  1786.  
  1787. /* Append the contents of the line 'from' to the line 'to'.
  1788.    This routine will work even if the line 'from' contains nulls */
  1789. void
  1790. line_append (from, to)
  1791.      struct line *from, *to;
  1792. {
  1793.   if (from->length > (to->alloc - to->length))
  1794.     {
  1795.       to->alloc += from->length;
  1796.       to->text = ck_realloc (to->text, to->alloc);
  1797.     }
  1798.   bcopy (from->text, to->text + to->length, from->length);
  1799.   to->length += from->length;
  1800. }
  1801.  
  1802. /* Append 'length' bytes from 'string' to the line 'to'
  1803.    This routine *will* append bytes with nulls in them, without
  1804.    failing. */
  1805. void
  1806. str_append (to, string, length)
  1807.      struct line *to;
  1808.      char *string;
  1809.      int length;
  1810. {
  1811.   if (length > to->alloc - to->length)
  1812.     {
  1813.       to->alloc += length;
  1814.       to->text = ck_realloc (to->text, to->alloc);
  1815.     }
  1816.   bcopy (string, to->text + to->length, length);
  1817.   to->length += length;
  1818. }
  1819.  
  1820. void
  1821. usage ()
  1822. {
  1823.   fprintf (stderr, "\
  1824. Usage: %s [-nV] [--quiet] [--silent] [--version] [-e script]\n\
  1825.         [-f script-file] [--expression=script] [--file=script-file] [file...]\n",
  1826.        myname);
  1827.   exit (4);
  1828. }
  1829.